/*********************************************************************************
 *      Copyright:  (C) 2022 Li Yanting<liyanting2@163.com>
 *                  All rights reserved.
 *
 *       Filename:  client_sqlite.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(05/10/2022)
 *         Author:  Li Yanting <liyanting2@163.com>
 *      ChangeLog:  1, Release initial version on "06/22/2022 12:47:16"
 *                 
 ********************************************************************************/

#include "client_sqlite.h"

int sql_init(sqlite3 **db, char *table_name)
{
    char                buffer[256];
    char               *zerrmsg = 0;
	char               *a = "(NAME INT NOT NULL, TIME CHAR(50) NOT NULL, TEMPER FLOAT NOT NULL);";

	int                 rv;

	rv = sqlite3_open(DATABASE_PATH, db);
	if(rv != SQLITE_OK )
    {
		return -1;
    }

	sprintf(buffer, "CREATE TABLE %s %s", table_name, a);
	
    rv = sqlite3_exec(*db, buffer, 0, 0, &zerrmsg);
    if ( rv != SQLITE_OK )
    {
		log_error("sql init failure: %s\n", zerrmsg);
        return 0;
    }

	return 0;
}

/*********************************************************************************
 *      function name:  sql_insert
 *        Description:  insert data to statement
 *       return value:  On error, -1 is returned. On success, 0 is returned.
 *          parameter:  db; statement name; current format time; temper.
 ********************************************************************************/
int sql_insert(sqlite3 *db, char *table_name, char *format_time, float temper)
{
    char        cmd[128];
    char       *insert_err;

    sprintf(cmd, "INSERT INTO %s VALUES ('%s', '%s', '%f')", table_name, table_name, format_time, temper);

    if( sqlite3_exec(db, cmd, 0, 0, &insert_err) != SQLITE_OK )
    {
		log_error("insert data to [%s] failure: %s\n", table_name, insert_err);
        return -1;
    }

    return 0;
}


int sql_check(sqlite3 *db, iotd_ctx_t *st_iotd, char *table_name)
{
	char 		 sql_cmd[64];
	char 		*check_err = NULL;
	char       **getdata;
	int          nRow = 0;
	int          nColumn = 0;

	sprintf(sql_cmd, "SELECT * FROM %s limit 1;", table_name);

	if( sqlite3_get_table(db, sql_cmd, &getdata, &nRow, &nColumn, &check_err) != SQLITE_OK ) 
	{
		log_error("sqlite3_get_table failure.\n");
		sqlite3_free_table(getdata);
		return -1;
	}

	if(  0 == nRow )
	{
		return -1;
	}
	else
	{
		strcpy(st_iotd->st_collect.time, getdata[4]);
		st_iotd->st_collect.temper = atof(getdata[5]);
		
		return 0;
	}
		
}


int sql_delete(sqlite3 *db, char *table_name)
{
	char        sql_cmd[64];
	char       *delete_err;

	sprintf(sql_cmd, "DELETE from %s limit 1;", table_name);

	if( sqlite3_exec(db, sql_cmd, 0, 0, &delete_err) != SQLITE_OK )
	{
		return -1;
	}
	return 0;
}

